<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/11/28
 * @time: 15:18
 */
namespace HuoKit\HuoServer\Adapter\ThinkPHP;

use HuoKit\HuoServer\Adapter\IRequestHandler;
use swoole_http_request as SwooleHttpRequest;
use swoole_http_response as SwooleHttpResponse;
use think\App;

class RequestHandler implements IRequestHandler
{
    public function handle(SwooleHttpRequest $swooleRequest, SwooleHttpResponse $swooleResponse,$manager=null)
    {
        $this->initGPC($swooleRequest,$swooleResponse,$manager);
        try {
            ob_start();
            App::run()->send();
            $content = ob_get_contents();
            ob_end_clean();
        }catch(\Exception $e){
            $content = $e->getMessage();
        }
        $swooleResponse->end($content);
    }

    protected function initGPC($swooleRequest,$swooleResponse,$manager)
    {
        $_GET = $_POST = $_COOKIE = $_SERVER = $_FILES = [];
        $GLOBALS['REQUEST'] = $swooleRequest;
        $GLOBALS['RESPONSE'] = $swooleResponse;
        if($manager) {
            $GLOBALS['MANAGER'] = $manager;
        }

        if(isset($swooleRequest->get)){
            $_GET = $swooleRequest->get;
        }

        if(isset($swooleRequest->post)){
            $_POST = $swooleRequest->post;
        }
        if(isset($swooleRequest->server)){
            $_SERVER = $swooleRequest->server;
        }
        if(isset($swooleRequest->cookie)){
            $_COOKIE = $swooleRequest->cookie;
        }
        if(isset($swooleRequest->files)){
            $_FILES = $swooleRequest->files;
        }
    }
}